<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\AuthRequest;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Facades\JWTAuth;

class AuthController extends Controller
{

    /**
     * @param AuthRequest $request
     * @return mixed
     */
    public function login(AuthRequest $request)
    {
        $user = $request->only(['phone', 'password']);
        $token = Auth::guard('api')->attempt($user);
        if ($token) {
            try {
                JWTAuth::setToken($token)->invalidate();
            } catch (TokenExpiredException $e) {
                //因为让一个过期的token再失效，会抛出异常，所以我们捕捉异常，不需要做任何处理
            }
            return $this->setToken($token)->success(['access_token' => $token]);
        }
        return $this->failed('账号或密码错误', 400);
    }

    /**
     * 返回当前登录用户信息
     * @return mixed
     */
    public function info()
    {
        $user = Auth::guard('api')->user();
        var_dump($user);exit;
        return $this->success($user);
    }

    /**
     * 注册接口
     * @param AuthRequest $request
     * @return mixed
     */
    public function register(Request $request)
    {
        $member = [
            'password' => bcrypt($request->password),
            'phone' => $request->phone,
            'name' => $request->phone,
        ];
        if(User::create($member)) {
            unset($member['name']);
            $token = Auth::guard('api')->attempt(['password' => $request->password, 'phone' => $request->phone]);
            return $this->success(['access_token' => $token]);
        } else {
            return $this->failed('用户注册失败');
        }
    }
}
